import Vue from 'vue'
import { Store } from 'vuex'

const state = {
  store_token: localStorage.getItem('store_token')
    ? JSON.parse(localStorage.getItem('store_token'))
    : '',
  store_userInfo: localStorage.getItem('store_userInfo')
    ? JSON.parse(localStorage.getItem('store_userInfo'))
    : {},
  store_loginInfo: localStorage.getItem('store_loginInfo')
    ? JSON.parse(localStorage.getItem('store_loginInfo'))
    : {},
  store_goodsInfo: localStorage.getItem('store_goodsInfo')
    ? JSON.parse(localStorage.getItem('store_goodsInfo'))
    : [],
  store_pageName: localStorage.getItem('store_pageName')
    ? JSON.parse(localStorage.getItem('store_pageName'))
    : '首页'
}
const getters = {
  store_token: (state) => state.store_token,
  store_userInfo: (state) => state.store_userInfo,
  store_loginInfo: (state) => state.store_loginInfo,
  store_goodsInfo: (state) => state.store_goodsInfo,
  store_pageName: (state) => state.store_pageName
}
const mutations = {
  // 存储购买过的商品
  set_goodsInfo(state, val) {
    console.log('store_goodsInfo', state, val)
    localStorage.setItem('store_goodsInfo', JSON.stringify(val))
    state.store_goodsInfo = val
  },
  // 存储账号密码
  set_loginInfo(state, val) {
    localStorage.setItem('store_loginInfo', JSON.stringify(val))
    state.store_loginInfo = val
  },
  // 设置token
  set_token(state, val) {
    localStorage.setItem('store_token', JSON.stringify(val))
    state.store_token = val
  },
  // 登录用户信息
  set_userInfo(state, val) {
    localStorage.setItem('store_userInfo', JSON.stringify(val))
    state.store_userInfo = val
  },
  // 页面名称
  set_pageName(state, val) {
    localStorage.setItem('store_pageName', JSON.stringify(val))
    state.store_pageName = val
  }
}
const actions = {
  get_userInfo({ commit }) {
    Vue.prototype
      .httpGet(Vue.prototype.API.API_userInfo, {
        id: state.store_userInfo.id
      })
      .then((res) => {
        commit('set_userInfo', res.data)
        console.log('set_userInfo', res.data)
      })
      .catch((err) => {
        console.error(err)
      })
  }
}

export default {
  state,
  getters,
  actions,
  mutations
}
